#!/usr/bin/python
# client.py
# Copyright (C) Vincenzo Tilotta 2011 <tailot@gmail.com>
#
# client.py is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# client.py is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
import os, sys, socket, threading, time, warnings, random
from ping import quiet_ping
from defs import *
from auth import auth
warnings.filterwarnings("ignore")
def main():
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.settimeout(60)
	s.connect((HOSTSERVER, PORTSERVER))
	sslSocket = socket.ssl(s)
	mytime = ''	
	if AUTHENABLE:
		mytime = auth(sslSocket)
	sslSocket.write('SERVICE_01')
	#riceve lista dei nodi disponibili
	ping_node = []
	list_nodes = sslSocket.read().split("\n")
	for node in list_nodes:
		try:		
			ping_node.append({int(quiet_ping(node)[2]) : node})

		except:
			#solo se non si ha accesso root (test in lab)
			read_latency = ( os.popen("ping -c 1 "+node+" | grep time= | awk {'print $8'} | tr '=' ' ' | awk {'print $2'}").read() ).replace("\n","")
			if read_latency != '':
				latency = int(round(float(read_latency),0))
				ping_node.append({latency : node})
	ping_node.sort()
	if not len(ping_node):
		print "Please disable Firewall!!! Enable random cpu."
		for node in list_nodes:
			random.seed()
			ping_node.append({random.randint(0, 100) : node})
	if DEBUG:	
		print ping_node		
	node_win = ''
	for i in ping_node:
		for j in i.keys():	
			node_win = i[j]
			break
		break
	sslSocket.write(node_win)
	play_service = sslSocket.read()
	if DEBUG:
		print play_service
	#chiudo la connessione con il server
	s.close()
	time.sleep(2)
	os.system(play_service+" -passwd "+mytime+" -AutoSelect=0")
	os.remove("mytime")
	sys.exit(0)
	

if __name__ == "__main__":
    sys.exit(main())
